package com.yenlien.traceyun.business.service;

import com.yenlien.traceyun.business.dao.GradeDao;
import com.yenlien.traceyun.business.entity.Grade;
import com.yenlien.traceyun.business.service.rest.usercenter.FileRestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.*;
import java.util.*;

/**
 * Created by LiuSha on 2020/7/27.
 */
@Service
public class GradeService {
    @Autowired
    private GradeDao gradeDao;
    @Autowired
    private FileRestService fileRestService;

    public Page<Grade> findByList(final Grade grade) {
        Pageable pageable = PageRequest.of(grade.getPage(), grade.getPageSize(), Sort.Direction.DESC, "createtime");
        return gradeDao.findAll(new Specification<Grade>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<Grade> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> companyId = root.get("companyId");
                //构造查询条件
                List<Predicate> list = new ArrayList<>();
                if (!StringUtils.isEmpty(grade.getCompanyId())) {
                    list.add(cb.equal(companyId, grade.getCompanyId()));
                }
                if (!StringUtils.isEmpty(grade.getProductName())) {
                    list.add(cb.equal(root.get("productName"), "%" + grade.getProductName() + "%"));
                }
                Predicate[] predicate = new Predicate[list.size()];
                return cb.and(list.toArray(predicate));
            }
        }, pageable);
    }

    public void save(Grade grade, List<MultipartFile> files) throws Exception {
        fileRestService.upload(null, grade, files);
        gradeDao.save(grade);
    }

    public void update(Grade grade, List<MultipartFile> files) throws Exception {
        fileRestService.upload(gradeDao.findById(grade.getId()), grade, files);
        gradeDao.save(grade);
    }

    public Grade findById(String id) {
        Grade grade = gradeDao.findById(id);
        return grade;
    }

    public void delete(String id) {
        gradeDao.deleteById(id);
    }

}
